package com.feonix.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CharsetUtil {

	private final static Log logger = LogFactory.getLog(CharsetUtil.class);

	public static final String US_ASCII = "US-ASCII";
	public static final String ISO_8859_1 = "ISO-8859-1";
	public static final String UTF_8 = "UTF-8";
	public static final String UTF_16BE = "UTF-16BE";
	public static final String UTF_16LE = "UTF-16LE";
	public static final String UTF_16 = "UTF-16";
	public static final String GBK = "GBK";
	public static final String GB2312 = "GB2312";

	public static String toASCII(String str) {
		return changeCharset(str, Charsets.ASCII);
	}

	public static String toISO_8859_1(String str) {
		return changeCharset(str, Charsets.ISO_8859_1);
	}

	public static String toUTF_8(String str) {
		return changeCharset(str, Charsets.UTF_8);
	}

	public static String toUTF_16BE(String str) {
		return changeCharset(str, Charsets.UTF_16BE);
	}

	public static String toUTF_16LE(String str) {
		return changeCharset(str, Charsets.UTF_16LE);
	}

	public static String toUTF_16(String str) {
		return changeCharset(str, Charsets.UTF_16);
	}

	public static String toGBK(String str) {
		return changeCharset(str, Charsets.GBK);
	}

	public static String toGB2312(String str) {
		return changeCharset(str, Charsets.GB2312);
	}

	public static String changeCharset(String str, Charsets newCharset) {
		String str1 = convert(newCharset);
		if ((StringUtil.isNotEmpty(str)) && (StringUtil.isNotEmpty(str1))) {
			byte[] arrayOfByte = str.getBytes();
			try {
				str = new String(arrayOfByte, str1);
			} catch (Exception exception) {
				logger.error("changeCharset error", exception);
			}
		}
		return str;
	}

	public static String changeCharset(String str, Charsets oldCharset, Charsets newCharset) {
		String str1 = convert(oldCharset);
		String str2 = convert(newCharset);
		if ((StringUtil.isNotEmpty(str)) && (StringUtil.isNotEmpty(str1)) && (StringUtil.isNotEmpty(str2))) {
			try {
				byte[] arrayOfByte = str.getBytes(str1);

				str = new String(arrayOfByte, str2);
			} catch (Exception exception) {
				logger.error("changeCharset error", exception);
			}
		}
		return str;
	}

	public static String convert(Charsets charset) {
		String str = null;
		if (charset != null) {
			switch (charset.ordinal() + 1) {
			case 1:
				str = "US-ASCII";
				break;
			case 2:
				str = "ISO-8859-1";
				break;
			case 3:
				str = "UTF-8";
				break;
			case 4:
				str = "UTF-16BE";
				break;
			case 5:
				str = "UTF-16LE";
				break;
			case 6:
				str = "UTF-16";
				break;
			case 7:
				str = "GBK";
				break;
			case 8:
				str = "GB2312";
				break;

			}
		}

		return str;
	}

	public static enum Charsets {
		ASCII, ISO_8859_1, UTF_8, UTF_16BE, UTF_16LE, UTF_16, GBK, GB2312;
	}

}
